package com.yunpeng.aidevice.common.controllers;

import com.yunpeng.common.dto.Result;
import com.yunpeng.common.util.ParametersCheckUtil;
import com.yunpeng.task.TaskConfiguration;
import com.yunpeng.task.TaskView;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;

/**
 * TaskController
 *
 * @author : Moore(hemw)
 * @date : 2020-04-06
 */
@RestController
@RequestMapping("/api/tasks")
public class TaskController {

    /**
     * 定时任务停止
     *
     * @param taskClazz
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "stopTask", method = RequestMethod.POST)
    public Result<Integer> stopTask(@PathParam(value = "taskClazz") String taskClazz) {
        ParametersCheckUtil.isNotBlank(taskClazz, "无效的任务类名");
        TaskConfiguration.STOP_TASK_LIST.put(taskClazz, null);
        for (TaskView taskView : TaskConfiguration.TASK_VIEW_QUEUE) {
            String[] taskName = taskView.getThreadName().split("-");
            if (taskName[0].equalsIgnoreCase(taskClazz)) {
                taskView.setStop(true);
                if (!taskView.getTask().isDone()) {
                    taskView.getTask().cancel(false);
                }
                if (!taskView.getExecutorService().isTerminated()) {
                    taskView.getExecutorService().shutdownNow();
                }
            }
        }
        return Result.success(TaskConfiguration.TASK_VIEW_QUEUE.size());
    }

}
